package org.sgtools.gwt.delegate.resolver;

import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.http.HttpServletRequest;
import org.sgtools.gwt.delegate.ServiceResolver;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import com.google.gwt.user.client.rpc.RemoteService;

public class RegxpURLServiceResolver implements ServiceResolver, ApplicationContextAware, InitializingBean{
	
	public static final String DEFAULT_URL_PATTERN = ".*/([\\w]*).gwt";
	
	private ApplicationContext applicationContext;

	private Pattern urlPatternCompiled;
	
	private String urlPattern = DEFAULT_URL_PATTERN;


	
	@Override
	public RemoteService getService(HttpServletRequest request) {
		String serviceName = getServiceName(request.getRequestURI()); 
		Object service = applicationContext.getBean(serviceName);
		if (!(service instanceof RemoteService)){
			throw new IllegalStateException("Service " + serviceName + " is not com.google.gwt.user.client.rpc.RemoteService");
		}
		return (RemoteService) service;
	}
	
	
	private String getServiceName(String url){
		Matcher m = urlPatternCompiled.matcher(url);
		if (m.matches()){
			return m.group(1);
		} else {
			throw new IllegalStateException("URL " + url + " is not matches");
		}
	}
	
	
	@Override
	public void setApplicationContext(ApplicationContext applicationContext)
			throws BeansException {
		this.applicationContext = applicationContext;
	}
	
	
	@Override
	public void afterPropertiesSet() throws Exception {
		urlPatternCompiled = Pattern.compile(urlPattern);
	}
	
	
	public void setUrlPattern(String urlPattern) {
		this.urlPattern = urlPattern;
	}

}
